<template>
	<view class="bg-[#F5F5F5]">
		<view class="mt-21rpx pb-32rpx">
			<chat-item v-for="(chat, index) in chatList" :key="index" :chat="chat" :index="index" :active="true"
				@click="handleChatClick(chat)" />
			<!-- 添加加载状态和加载完成的提示 -->
			<view v-if="chatList.length <= 0" class="empty-state flex-center flex-col mt-200rpx">
				<wd-status-tip :image="emptyImage" tip="暂无讨论组数据" />
			</view>

			<wd-loadmore v-if="chatList.length > 0" finished-text="已经全部加载完毕" state="finished"></wd-loadmore>
		</view>
	</view>
</template>

<script setup lang="ts">
	import { ref, reactive } from 'vue'
	import ChatItem from '@/components/chat-item/chat-item.vue'
	import { useGroupStore, useChatStore } from '@/store'
	import { initChat } from '@/utils/chatSocket'
	/* 引入 暂无数据 - 图片 */
	import emptyImage from '@/static/images/icons/empty.png'
	
	const groupStore = useGroupStore()
	const chatStore = useChatStore()

	const props = defineProps({
		searchValue: {
			type: String,
		},
	})
	const chatList = ref(null)
	function handleInfo() {
		chatList.value = chatStore.chats
	}
	onShow(() => {
		handleInfo()
		setTimeout(() => {
			initChat()
		}, 5000)
	})
	watch(
		() => chatStore.chats,
		(newVal, oldLen) => {
			chatStore.sortChatGroup()
			chatList.value = newVal
		},
		{
			deep: true, // 启用深度监听
		},
	)
	watch(
		() => props.searchValue,
		() => {
			if (props.searchValue) {
				const filteredArray = chatStore.chats.filter((item) => {
					return item.showName.includes(props.searchValue)
				})
				chatList.value = JSON.parse(JSON.stringify(filteredArray))
			} else {
				chatList.value = chatStore.chats
			}
		},
	)

	const handleChatClick = (chat : any) => {
		const group = groupStore.groups.find((item) => item.id === chat.targetId)
		if (group && group.id) {
			if (group.dissolve) {
				uni.showToast({
					title: '该群聊已解散!',
					icon: 'none',
					duration: 1500,
				})
			} else {
				if (!(chatStore.chats && chatStore.chats.length > 0)) {
					const chatInfo = {
						type: 'GROUP',
						targetId: chat.targetId,
						showName: chat.name,
						headImage: chat.headImage,
					}
					chatStore.openChat(chatInfo)
				}
				uni.navigateTo({
					url: `/pages/chat/detail?id=${chat.targetId}`,
				})
			}
		}
	}

	// 添加搜索和tab相关的变量
	const currentTab = ref(0)

	const handleTabClick = (index : number) => {
		currentTab.value = index
	}
</script>

<style lang="scss" scoped>
	:deep(.wd-divider) {
		justify-content: center;
		margin: 0;
	}

	:deep(.wd-divider::before) {
		border-color: #eeeeee;
	}

	:deep(.wd-divider::after) {
		border-color: #eeeeee;
	}
</style>